package logger

import (
	"os"
	"time"
	"github.com/kataras/golog"
	"until/yml"
	"fmt"
	"tools/normal"
)

var logger *golog.Logger

func Init(gl *golog.Logger)  {
	logger=gl
	logger.SetOutput(LogFile())
}

func LogFile() *os.File {
	filename := todayFilename()
	fmt.Println("logfile:"+filename)
	// open an output file, this will append to the today's file if server restarted.
	f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		if os.IsNotExist(err){
			err := os.Mkdir(yml.Dir+"/log", os.ModePerm)
			if err != nil {
				fmt.Println(err)
				return nil
			}
		}
	}
	if normal.FileExist(filename){
		f, err = os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	}else {
		f,err=os.Create(filename)
		f, err = os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	}
	if err != nil {
		panic(err.Error())
	}
	return f
}
func todayFilename() string {
	today := time.Unix(time.Now().Unix(), 0).Format("2006-01-02")
	return yml.Dir+"/log/"+today + ".txt"
}
func Info(v ...interface{}) {
	logger.Info(v)
}

func Infof(format string, v ...interface{}) {
	logger.Infof(format,v)
}

func Warn(v ...interface{}) {
	logger.Warn(v)
}

func Warnf(format string, v ...interface{}) {
	logger.Warnf(format, v...)
}

func Error(v ...interface{}) {
	logger.Error(v)
}

func Errorf(format string, v ...interface{}) {
	logger.Errorf(format, v...)
}

func Fatal(v ...interface{}) {
	logger.Fatal(v)
}

func Fatalf(format string, v ...interface{}) {
	logger.Fatalf(format, v...)
}
func Debugf(format string, v ...interface{}) {
	logger.Debugf(format, v...)
}
func Debug(v ...interface{}) {
	logger.Debug( v...)
}